<template>
  <div class="app-container hk-flex-column">
    <search-form
      :data="queryParams"
      :field-list="fieldList"
      :list-type-info="dictList"
      :is-asset="true"
      style="padding-bottom: 0rem"
      @handleSearch="handleQuery"
      @handleReset="resetQuery" />
    <el-row style="position: absolute; right: 20px; top: 50px">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
    </el-row>
    <hk-table
      :table-data="tableData"
      :table-columns="tableList"
      :selection="false"
      :show-index="true"
      :total="total"
      :loading="loading"
      :table-height="80"
      operate
      :common-fixed="true"
      :operate-width="112"
      :query-params="queryParams"
      @changePage="getDataList">
      <!-- 操作权限 -->
      <template #departmentIds="scope">
        <div class="my-range" style="width: 100%">
          <span class="my-sp1">责任部门：</span><span class="my-sp2">{{ scope.row.departmentName }}</span>
        </div>
        <div class="my-range">
          <span class="my-sp1">存放区域：</span><span class="my-sp2">{{ scope.row.positionName }}</span>
        </div>
        <div class="my-range">
          <span class="my-sp1">设备类型：</span><span class="my-sp2">{{ scope.row.assetTypeName }}</span>
        </div>
      </template>
      <template #inventoryStatus="scope">
        <div v-if="scope.row.inventoryStatus == '1'">
          <span>未盘点</span>
        </div>
        <div v-else class="my-tags">
          <el-tag hit effect="plain" size="mini" type="info">未盘点：{{ scope.row.notInventoried || 0 }}</el-tag>
          <el-tag hit effect="plain" size="mini" type="warning">账实相符：{{ scope.row.accountsMatch || 0 }}</el-tag>
          <el-tag hit effect="plain" size="mini">变更：{{ scope.row.changeQuantity || 0 }}</el-tag>
          <el-tag hit effect="plain" size="mini" type="success">盘盈：{{ scope.row.inventoryProfit || 0 }}</el-tag>
          <el-tag hit effect="plain" size="mini" type="danger">盘亏：{{ scope.row.inventoryLoss || 0 }}</el-tag>
        </div>
      </template>
      <template #operate="scope">
        <!-- <el-button size="mini" type="text" @click="handleDetail(scope.row)">编辑</el-button>
        <el-button size="mini" type="text" @click="handleDetail(scope.row)">删除</el-button>
        <el-button size="mini" type="text" @click="handleDetail(scope.row)">导出盘点对象</el-button>
        <el-button size="mini" type="text" @click="handleDetail(scope.row)">导入盘点结果</el-button> -->

        <div class="my-operate" :class="scope.row.inventoryStatus !== '1' ? 'isdel' : ''">
          <span size="mini" type="text" @click="handleEdit(scope.row)">编辑</span>
          <span v-if="scope.row.inventoryStatus == '1'" size="mini" type="text" @click="handleDelete(scope.row)"
            >删除</span
          >
        </div>
        <div class="my-operate">
          <span size="mini" type="text" @click="handleExport(scope.row)">导出盘点任务</span>
        </div>
        <div class="my-operate">
          <span size="mini" type="text" @click="handleImport(scope.row)">导入盘点结果</span>
        </div>
        <div v-if="scope.row.inventoryStatus !== '1'" class="my-operate">
          <span size="mini" type="text" @click="handleLook(scope.row)">查看盘点结果</span>
        </div>
      </template>
    </hk-table>
    <hk-upload
      ref="import_dia"
      :url="url"
      title="导入盘点结果"
      :accept="accept"
      :multiple="false"
      @submit="getDataList" />
  </div>
</template>

<script>
import { getDict, dictItemsList } from '@/api/specialProject/assetRecords'
import { pageList, delItem, exportData } from '@/api/specialProject/Inventory'

import SearchForm from '@/components/HkSearchform/index.vue'
import HkTable from '@/components/Hk-Table/index.vue'

export default {
  components: {
    SearchForm,
    HkTable,
  },
  beforeRouteLeave(to, from, next) {
    console.log(to, '路由')
    if (to.path === '/specialProject/assets/assetLibraryDetail') {
      const condition = JSON.stringify(this.queryParams)
      sessionStorage.setItem('condition', condition)
    } else {
      sessionStorage.removeItem('condition')
    }
    next()
  },
  beforeRouteEnter(to, from, next) {
    console.log(to, '路由')
    if (from.path !== '/specialProject/assets/assetLibraryDetail') {
      sessionStorage.removeItem('condition')
    }
    next()
  },
  data() {
    return {
      url: window.baseUrl.action + '/assetInventory/upload',
      title: '导入盘点结果',
      accept: '.xlsx',
      assetProps: {
        children: 'children',
        label: 'dictValue',
        value: 'id',
        emitPath: false,
        multiple: true,
      },
      queryParams: {
        current: 1,
        size: 10,
      },
      checkedList: [],
      ids: [],
      tableData: [],
      total: 0,
      loading: false,
      tableList: [
        { label: '任务名称', param: 'taskName' },
        { label: '盘点范围', param: 'departmentIds', type: 'slot' },
        { label: '盘点统计', param: 'inventoryStatus', type: 'slot', width: '350px' },
        { label: '操作人', param: 'userName', width: '120px' },
        { label: '创建时间', param: 'createTime', width: '160px' },
        { label: '更新时间', param: 'updateTime', width: '160px' },
      ],
      // 搜索框
      fieldList: [
        {
          label: '任务名称',
          type: 'input',
          field: 'taskName',
          maxlength: 20,
          placeholder: '请输入任务名称',
        },
        {
          label: '盘点状态',
          type: 'select',
          field: 'inventoryStatus',
          maxlength: 20,
          list: 'inventoryStatusList',
          width: '150px',
        },
      ],
      citiesList: [],
      assetValue: [],
      nodeList: [],
      resArr: [],
      dictList: {
        typeList: [],
        inventoryStatusList: [],
      },
    }
  },
  created() {
    var cd = sessionStorage.getItem('condition')
    if (cd) {
      var condition = JSON.parse(cd)
      this.queryParams = condition
    }
  },
  mounted() {
    this.getDataList()
    this.getDictDatas()
  },
  methods: {
    // 盘点结果
    handleLook(row) {
      console.log(row)
      this.$router.push({
        path: '/specialProject/assets/InventoryResult',
        query: {
          title: '盘点结果',
          id: row.id,
        },
      })
    },
    toDetail(row) {
      console.log(row)
      this.$router.push({
        path: '/specialProject/assets/assetLibraryDetail',
        query: {
          id: row.assetId,
          title: '详情',
          dictValue: row.dictItems.dictValue,
          dictKey: row.dictItems.dictKey,
          dictId: row.dictItems.id,
        },
      })
    },
    handleAdd(row) {
      console.log(row)
      this.$router.push({
        path: '/specialProject/assets/InventoryDetail',
        query: {
          title: '新增',
        },
      })
    },
    handleEdit(row) {
      console.log(row)
      this.$router.push({
        path: '/specialProject/assets/InventoryDetail',
        query: {
          title: '修改',
          id: row.id,
        },
      })
    },
    /** 导入按钮操作 */
    handleImport(e) {
      // this.upData = {
      //   taskId: e.id,
      // }
      this.$refs.import_dia.show(e.id)
    },
    // 导出
    handleExport(e) {
      var obj = {
        departmentIds: [],
        assetTypes: [],
        positionIds: [],
        taskId: e.id,
      }
      if (e.departmentIds === '—') {
        obj.departmentIds = []
      } else {
        obj.departmentIds = e.departmentIds
      }
      if (e.assetTypes === '-') {
        obj.assetTypes = []
      } else {
        obj.assetTypes = e.assetTypes
      }
      if (e.positionIds === '-') {
        obj.positionIds = []
      } else {
        obj.positionIds = e.positionIds
      }
      this.smDownload(
        window.baseUrl.action + '/assetInventory/export',
        obj,
        `${e.taskName}${new Date().getTime()}.xlsx`
      )
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal
        .confirm('是否确认删除所选数据项？')
        .then(function () {
          return delItem(id)
        })
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.getDataList()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    async clearSelect(e) {
      const result = this.nodeList.filter((item) => e.includes(item.value))
      if (!result) {
        this.assetValue = []
        this.citiesList = []
        this.queryParams.assetTypes = []
      } else {
        this.nodeList = result
        const idArr = []
        this.citiesList = []
        for (let i = 0; i < result.length; i++) {
          idArr.push(result[i].value)
          this.citiesList.push(result[i].data)
        }
        this.assetValue = idArr
        this.resArr = []
        await this.getNodeId(result)
        this.queryParams.assetTypes = this.resArr
      }
    },
    getNodeId(array) {
      for (var item of array) {
        this.resArr.push(item.value)
        if (item.children.length > 0) {
          this.getNodeId(item.children)
        }
      }
    },
    selectFocus() {
      var that = this
      this.$refs.selectIt.blur()
      var timer = setInterval(() => {
        that.$refs.cascader.toggleDropDownVisible(true)
        clearInterval(timer)
      }, 200)
    },
    // 级联框
    handleChange(e, item) {
      if (!e) {
        this.assetValue = []
        this.citiesList = []
      } else {
        let nodeList = this.$refs[item].getCheckedNodes()
        // 如果三级全选就显示二级的，没有全选就显示三级的
        nodeList = nodeList.filter((option) => !(option.parent && option.parent.checked))
        this.nodeList = nodeList
        const idArr = []
        this.citiesList = []
        for (let i = 0; i < nodeList.length; i++) {
          idArr.push(nodeList[i].value)
          this.citiesList.push(nodeList[i].data)
        }
        this.assetValue = idArr
      }
    },
    // 解决级联选死机问题
    expandChange() {
      this.$nextTick(() => {
        // 添加这段代码
        const $el = document.querySelectorAll('.el-cascader-panel .el-cascader-node[aria-owns]')
        Array.from($el).map((item) => item.removeAttribute('aria-owns'))
      })
    },
    handleRecord(row) {
      this.$refs.record_drawer.show(row.id)
    },
    //  查询
    handleQuery() {
      this.queryParams.current = 1
      this.getDataList()
    },
    //  重置
    resetQuery() {
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.assetValue = []
      this.citiesList = []
      this.getDataList()
    },

    getDataList(val) {
      this.loading = true
      pageList(this.queryParams).then((res) => {
        res.list.forEach((element) => {
          for (const key in element) {
            if (key !== 'departmentIds' && key !== 'assetTypes' && key !== 'positionIds') {
              element[key] = element[key] !== null ? element[key] : '—'
            }
          }
        })
        this.loading = false
        this.tableData = res.list
        this.total = res.total
        const condition = JSON.stringify(this.queryParams)
        sessionStorage.setItem('condition', condition)
      })
    },
    // 字典获取
    getDictDatas() {
      // 类型
      getDict({ code: 'inventoryStatus' }).then((res) => {
        this.dictList.inventoryStatusList = res.map((o) => {
          o.label = o.dictValue
          o.value = o.dictKey
          return o
        })
      })

      dictItemsList({ parentId: 0 }).then((res) => {
        this.dictList.typeList = res
      })
    },
  },
}
</script>
  
    <style lang="scss" scoped>
#app.dark-theme {
  .app-container {
    background: transparent !important;
    color: #fff !important;
  }
  .my-sp1 {
    padding: 6px;
    background: #e7edf862;
    border-radius: 4px 0 0 4px;
  }
  .my-sp2 {
    padding: 6px;
    background: #d4dff360;
    border-radius: 0 4px 4px 0;
  }
}
.my-operate {
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #4b6eef;
  padding: 0 10px;
}
.isdel {
  display: block;
  text-align: center;
}
.my-range {
  // display: flex;
  // justify-content: flex-start;
  font-size: 12px;
  // padding: 0 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-bottom: 4px;
  .my-sp1 {
    padding: 6px;
    background: #e7edf8;
    border-radius: 4px 0 0 4px;
  }
  .my-sp2 {
    padding: 6px;
    background: #d4dff3;
    border-radius: 0 4px 4px 0;
  }
}
.my-tags {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 12px;
  flex-wrap: wrap;

  .el-tag {
    margin-right: 4px;
    margin-bottom: 4px;
  }
}
.ca-select {
  width: 220px;
  min-height: 32px;
  cursor: pointer;
  .fake {
    float: left;
    z-index: 9;
  }
  .test {
    float: left;
    visibility: hidden;
    width: 0px;
    height: 0px;
    z-index: -1;
  }
}
.el-row {
  position: absolute;
  right: 20px;
  top: 50px;
}
.total-title {
  margin-bottom: 15px;
  margin-top: 6px;
  line-height: 24px;
}
.font-size16 {
  font-size: 16px;
}
.flex-1 {
  flex: 1;
  justify-content: space-between;
  height: 100%;
}
.font-c-blue {
  color: #4b6eef;
  font-size: 36px;
}
.mt-20 {
  margin-top: 20px;
}
::v-deep {
  .content {
    padding-bottom: 0;
  }
}
</style>
  
  